import { useLocation, Navigate } from "react-router-dom";
import { AxiosCanceler } from "../../api/helper/axiosCancel";
import { searchRoute, handleRouter } from "../../utils/util";
import { allRouters } from "../routes";
import { store } from '../../redux'
import { setPageTitleActionThunk } from '../../redux/modules/menu/action'
import { home_path } from "../../utils/system/system";

const axiosCanceler = new AxiosCanceler();

/**
 * @description 路由守卫组件
 * */
const AuthRouter = (props) => {
	const { pathname } = useLocation();
  const route = searchRoute(pathname, allRouters);
  // * 在跳转路由之前，清除所有的请求
  axiosCanceler.removeAllPending();
  // * 跳转之前先设置当前页面标题
  store.dispatch(setPageTitleActionThunk(route.meta?.titleI18n ?? ''))
  // * 判断当前路由是否需要访问权限(不需要权限直接放行)
  if (!route.meta?.requiresAuth ?? true) return props.children;
  // * 判断是否需要重定向，如果需要重定向则直接跳转
  if (route.redirect) return <Navigate to={route.redirect} />;
  // * 判断是否有Token
  const token = store.getState().auth.token;
  if (!token) return <Navigate to="/login" replace />;
  // * Dynamic Router(动态路由，根据后端返回的菜单数据生成的一维数组)
  // let dynamicRouter = store.getState().menu.menuList;
  let dynamicRouter = store.getState().auth.userInfo.isAdmin ? allRouters : store.getState().menu.menuList
  dynamicRouter = handleRouter(dynamicRouter, [])
  // * Static Router(静态路由，配置首页地址，使其暂时能够进入首页获取菜单,layout内置有loading，不用担心)
  // 必须要有404
  const staticRouter = [home_path, "/404"];
  const routerList = dynamicRouter.concat(staticRouter);
  // * 如果访问的地址没有在路由表中重定向到403页面
  if (routerList.indexOf(pathname) === -1) return <Navigate to="/404" />;
  // * 当前账号有权限返回 Router，正常访问页面
	return props.children;
};

export default AuthRouter